package com.example.toycarcontroller

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
import android.util.Log
import android.bluetooth.BluetoothGattService

class SharedViewModel(application: Application) : AndroidViewModel(application) {
    private val _bluetoothStatus = MutableLiveData<BluetoothStatus>(BluetoothStatus(false, ""))
    val bluetoothStatus: LiveData<BluetoothStatus> = _bluetoothStatus

    // 新增服务信息存储
    private val _bluetoothServices = MutableLiveData<List<BluetoothGattService>>(emptyList())
    val bluetoothServices: LiveData<List<BluetoothGattService>> = _bluetoothServices

    fun updateStatus(isConnected: Boolean, deviceName: String = "") {
        Log.d("SharedViewModel", "更新状态: 已连接=$isConnected, 设备=$deviceName")
        _bluetoothStatus.value = BluetoothStatus(isConnected, deviceName)
    }

    fun updateServices(services: List<BluetoothGattService>) {
        _bluetoothServices.value = services
    }

    // 单例实现
    companion object {
        @Volatile private var instance: SharedViewModel? = null

        fun getInstance(application: Application): SharedViewModel {
            return instance ?: synchronized(this) {
                // 确保Application上下文正确传递
                val appContext = application.applicationContext
                instance ?: SharedViewModel(application).also {
                    instance = it
                }
            }
        }
    }
}

data class BluetoothStatus(
    val isConnected: Boolean,
    val deviceName: String
)